import groovy.xml.MarkupBuilder
import javax.servlet.ServletRequest

class FeedGeneratorService {

  boolean transactional = false

  public String generateRssFeed(boolean includePrivateMessages, Map params, ServletRequest request) {
    def messages = []
    if (includePrivateMessages) {
      messages = Message.list(params)
    } else {
      messages = Message.findAllByIsPrivate(false, params)
    }
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    xml.rss(version: '2.0') {
      channel {
        title("MoTSangria Activity Log")
        link("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/all")
        description("MoTSangria activity log showing the last ${params.max} messages submitted to the MoTSangria homepage")
        for (m in messages) {
          item {
            title("${m.user}: ${m.content}")
            description("${m.user}: ${m.content} (via: ${m.medium} ${DateTagLib.getNiceDate(m.dateCreated)} ${m.isPrivate ? ', private message' : ''})")
            link("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/show/${m.id}")
            guid("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/show/${m.id}")
            pubDate("${m.dateCreated}")
          }
        }
      }
    }
    return writer.toString()
  }
}
